package com.yuncool.service;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.yuncool.auth.utils.SessionUser;
import com.yuncool.constants.CommonConstants;
import com.yuncool.domain.BbsComment;
import com.yuncool.domain.vo.CommentVO;
import com.yuncool.mapper.BbsCommentMapper;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

/**
 * @Auther XIE
 * @Date 2019/9/1 17:26
 * @Description TODO 社区评论服务类
 * @Version 1.0
 */
@Service
public class BbsCommentService {

	@Resource
	private BbsCommentMapper bbsCommentMapper;

	/**
	 * 获取评论列表
	 *
	 * @param bbsId
	 * @return
	 */
	public PageInfo<BbsComment> listBbsComment(String bbsId) {
		Example example = new Example(BbsComment.class);
		example.createCriteria().andEqualTo("bbsId", bbsId)
			.andEqualTo("isValid", CommonConstants.DATA_ISVALID).andEqualTo("partId", CommonConstants.DATA_ROOT);
		example.setOrderByClause("create_time DESC");
		PageHelper.startPage(1, 5);
		List<BbsComment> bbsComments = bbsCommentMapper.selectByExample(example);
		for (BbsComment bbsComment : bbsComments) {
			bbsComment.setSonBbsComment(getSonComment(bbsComment.getId(), bbsId));
		}
		PageInfo<BbsComment> pageInfo = new PageInfo<>(bbsComments);
		return pageInfo;
	}

	/**
	 * 获取评论的子评论
	 *
	 * @param id
	 * @param bbsId
	 * @return
	 */
	private List<BbsComment> getSonComment(Integer id, String bbsId) {
		Example example = new Example(BbsComment.class);
		example.createCriteria()
			.andEqualTo("bbsId", bbsId)
			.andEqualTo("partId", id)
			.andEqualTo("isValid", CommonConstants.DATA_ISVALID);
		example.setOrderByClause("create_time DESC");
		List<BbsComment> bbsComments = bbsCommentMapper.selectByExample(example);
		for (BbsComment bbsComment : bbsComments) {
			bbsComment.setSonBbsComment(getSonComment(bbsComment.getId(), bbsId));
		}
		return bbsComments;
	}

	/**
	 * 回复帖子或评论
	 *
	 * @param vo
	 */
	public void addComment(CommentVO vo) {
		BbsComment base = new BbsComment();
		base.setBbsId(Integer.parseInt(vo.getBbsId()));
		base.setContent(vo.getContent());
		base.setCreateTime(new Date());
		base.setAuthorMemberId(new SessionUser().getUserDetail().getUserId());
		base.setIsValid(CommonConstants.DATA_ISVALID);
		if (CommonConstants.COMMENT_BBS.equals(vo.getType())) {
			//评论帖子
			base.setPartId(Integer.parseInt(CommonConstants.DATA_ROOT));
		} else if (CommonConstants.COMMENT_IT.equals(vo.getType())) {
			//回复评论
			base.setPartId(Integer.parseInt(vo.getPartId()));
		}
		bbsCommentMapper.insertSelective(base);
	}

	/**
	 * 删除评论
	 *
	 * @param id
	 */
	public void delComment(Integer id) {
		BbsComment base = new BbsComment();
		base.setId(id);
		base.setIsValid(CommonConstants.DATA_NOT_ISVALID);
		bbsCommentMapper.updateByPrimaryKeySelective(base);
	}
}
